<?php
namespace PsiFramework\Applications\DefaultApp\Classes\Actions\User;

use PsiFramework\Classes\Util\UI\LanguageManager;

use PsiFramework\Classes\Util\Security\Tools\Encryption;

import("Classes.Actions.AbstractAction");
import("Classes.Model.ModelInterface.IUser");
import("Classes.Util.Object.EMail");
import("Classes.Util.UI.HTML");
import("Classes.Util.Manager.ParametersManager");
import("Plugins.Recaptcha.Classes.Tools.Captcha");

use \PsiFramework\Classes\Actions\AbstractAction;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Factory\ObjectFactory;
use \PsiFramework\Classes\Model\ModelInterface\IUser;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Classes\Util\Object\EMail;
use \PsiFramework\Classes\Util\Object\Image;
use \PsiFramework\Classes\Util\UI\HTML;
use \PsiFramework\Classes\Util\Manager\ParametersManager;
use \PsiFramework\Plugins\Recaptcha\Classes\Tools\Captcha;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The Register Action
 *
 * This action is used when a user wants to create an account
 *
 * @package Actions.User
 */
class RegisterAction extends AbstractAction
{

    /**
     * Function executed by the controller
     *
     * It shows the register form or registers a user
     *
     * @param User $user the user to display
     * 
     * @return Response the response to the action execution
     */
    public function execute(/*User*/ $user=null, /*string*/ $error=null)
    {

        if ($this->_request->getParameter("login")!=null
            && $this->_request->getParameter("password")!=null
            && $user===null
        ) {
            //if form has been submitted

            $pwd = $this->_request->getParameter("password");
            
            //creates a new user
            $user = ObjectFactory::getNewObject("User");
            $user->setLogin($this->_request->getParameter("login"));
            //encrypts the password
            $user->setPassword(Encryption::encrypt($pwd));

            //sets the other variables of the user
            if ($this->_request->getParameter("email") != null) {

                //set the email
                $user->setEmail($this->_request->getParameter("email"));
                
                $ok = $this->getUserParameters($user);
                
                if (!$ok) {
                    $user = null;
                }

            } else {
                //if the parameters weren't all present
                $user = null ;
            }

            if ($user != null) {
                $user->setCreationDate(Date::now());

                if ($pwd == $this->_request->getParameter("confirmPassword")) {
                    //if the password has been entered twice the same

                    $captcha = Captcha::getInstance();
                    if ($captcha->retrieveResponse()) {
                        //if the captcha response is ok

                        $userDao = DAOFactory::getDAO("User");
                        //saves the user
                        $ok = $userDao->save($user, true, false);

                        if ($ok) {
                            $ok = $this->afterCreation($user);
                            
                            if ($ok) {
                                $this->_response->setAttribute('message', LanguageManager::getInstance()->getText('REGISTERED'));
                                $this->findForward('success');
                            } else {
                                //if there has been a database error
                                //display the registration form anew
                                $this->execute($user, "Error after the user creation !");
                            }
                        } else {
                            //if there has been a database error
                            //display the registration form anew
                            $this->execute($user, "Database Error !");
                        }
                    } else {
                        //captcha error
                        $this->execute(
                            $user,
                            "Captcha error : ".$captcha->getError()
                        );
                    }
                } else {
                    //different passwords
                    $this->execute($user, "Password error !");
                }
            } else {
                //different passwords
                $this->execute($user, "Information error !");
            }
        } else {

            $this->_response->setAttribute('error', $error);
            $this->findForward('form');
        }
    }
    
    /**
     * Retrieves the parameters
     * 
     * @param User $user
     * 
     * @return boolean
     */
    public function getUserParameters(&$user)
    {
        return true;
    }

    /**
     * Sets the action to execute after the creation
     * 
     * @param User $user
     * 
     * @return boolean
     */
    public function afterCreation($user)
    {
        //if the database request succeeded
        
        //creation of the activation code
        $activationCode = uniqid();
        $activation = ObjectFactory::getNewObject("Activation");
        $activation->setUser($user);
        $activation->setActivationKey($activationCode);
        $activationDao = DAOFactory::getDAO("Activation");
        //saving of the activation object
        $ok = $activationDao->save($activation, true, false);
        
        if ($ok) {
        	//if the database request succeeded
        
        	$paramManager = ParametersManager::getInstance();
        	$applicationsParameters = $paramManager->getApplicationsParameters();
        
        	$link  = $this->_request->getHostURI();
        	$link .=
            	"?action=User.ConfirmRegistration&".
            	"activationKey=".$activationCode ;
        
        	$email = new EMail(
    	        $applicationsParameters->getContact(),
    			$user->getEmail(),
    			"Confirm Registration",
    			HTML::link($link, $link)
        	);
        	//send email to the user
        	$email->send();
        	//display the confirm registration form
        }
        
        return $ok;
    }
}
